package com.request.config.thread;

import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpTask;
import com.ejlchina.okhttps.OkHttps;
import com.request.common.utils.CustomBlockingQueue;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class ThreadConfig {

    @Bean
    public ThreadPoolExecutor handlerOrderExecutor(ServerConfigurer serverConfig) {
        return new ThreadPoolExecutor(serverConfig.getCorePoolSize(), serverConfig.getMaxPoolSize(),
                60, TimeUnit.SECONDS, new CustomBlockingQueue<>(serverConfig.getQueueCapacity()));
    }

    @Bean
    public HTTP http() {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequestsPerHost(100);
        return OkHttps.newBuilder().config(builder -> {
            builder.connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES));
            builder.connectTimeout(5, TimeUnit.SECONDS);
            builder.readTimeout(5, TimeUnit.SECONDS);
            builder.dispatcher(dispatcher);
        }).exceptionListener((HttpTask<?> task, IOException error) -> {
            // 返回 true 表示继续执行 task 的 OnException 回调，
            // 返回 false 则表示不再执行，即 阻断

            log.info("okhttp全局异常：", error);
            return false;
        }).build();
    }
}
